# coding:utf-8

from common.entities import Product, Products
from common.htmlparser import HtmlParser
import json


class ProductDetailsParser:
    __parser = None

    def __init__(self):
        self.__parser = HtmlParser()
        self.__parser.addrule('name', r'id="product_name_\d*?"[^<]*?<h1>(.*?)<')
        self.__parser.addrule('desc', r'<h3 itemprop="description" class="frg_r15_model_description">(.*?)</h3>')
        self.__parser.addrule('madein', r'<h3 class="frg_r15_model_description frg_r15_model_madein">[\r\t\n]*?'
                                        r'.*?&nbsp;(.*?)[\r\n\t]*?</h3>')
        self.__parser.addrule('colors', r'<label>Colour</label>[^>]*?>[^>]*?>[\r\t\n]*?([^\r\t\n]*?)[\r\t\n]*?<')
        self.__parser.addrule('sizes_block', r'<div class="selected">[\r\n\t]*?"Size".*?<ul>.(.*?)</ul>')
        self.__parser.addrule('size_value', r'value="(.*?)"')
        self.__parser.addrule('price', r'<span id="offerPrice_\d*?" class="frg_r15_model_price" itemprop="price">'
                                       r'.*?\D*?([\d\.,]*?)[\n\r\t]*?<')
        self.__parser.addrule('currency', r'<span id="offerPrice_\d*?" class="frg_r15_model_price" itemprop="price">'
                                          r'[\n\r\t]*?([^\d\r\t\n]*?) [\d\.,]*?[\n\r\t]*?<')
        self.__parser.addrule('img_block', r'var productThumbList = (\[.*?\]);')

    def __del__(self):
        self.__parser = None

    def find_name(self, src):
        if src is None:
            return None
        name = self.__parser.findall('name', src)
        if len(name) > 0:
            return name[0]
        else:
            return None

    def find_price(self, src):
        if src is None:
            return None
        price = self.__parser.findall('price', src)
        if len(price) > 0:
            return price[0]
        else:
            return None

    def find_currency(self, src):
        if src is None:
            return None
        currency = self.__parser.findall('currency', src)
        if len(currency) > 0:
            return currency[0]
        else:
            return None

    def find_desc(self, src):
        if src is None:
            return None
        desc = self.__parser.findall('desc', src)
        if len(desc) > 0:
            return desc[0]

    def find_madein(self, src):
        if src is None:
            return None
        madein = self.__parser.findall('madein', src)
        if len(madein) > 0:
            return madein[0]

    def findall_colors(self, src):
        if src is None:
            return None
        colors = self.__parser.findall('colors', src)
        if len(colors) > 0:
            return colors

    def findall_sizes(self, src):
        if src is None:
            return None
        sizes_blk = self.__parser.findall('sizes_block', src)
        if len(sizes_blk) == 0:
            return None
        sizes = self.__parser.findall('size_value', sizes_blk[0])
        if len(sizes) > 0:
            return sizes

    def findall_zoomed_images(self, src):
        if src is None:
            return None
        block = self.__parser.findall('img_block', src)
        if len(block) == 0:
            return None
        try:
            data = json.loads(block[0])
            if len(data) == 0:
                return None
            images = [] * 0
            for img in data:
                images.append(img['dataurl'])
            if len(images) == 0:
                return None
            return images
        except (KeyError, ValueError, TypeError) as e:
            print('[Error json parser] ' + str(e))

    def findall_main_images(self, src):
        if src is None:
            return None
        block = self.__parser.findall('img_block', src)
        if len(block) == 0:
            return None
        try:
            data = json.loads(block[0])
            if len(data) == 0:
                return None
            images = [] * 0
            for img in data:
                images.append(img['url'])
            if len(images) == 0:
                return None
            return images
        except (KeyError, ValueError, TypeError) as e:
            print('[Error json parser] ' + str(e))


class ProductUrlParser:
    __parser = None

    @staticmethod
    def findall_products(json_str):
        try:
            data = json.loads(json_str)
            parts = data['list']
            cat_id = data['categoryId']
            products = Products()
            for part in parts:
                part_no = part['partNumber']
                if not part_no.isdigit():
                    continue
                url = part['url']
                p = Product(part_no, None, url, cat_id)
                products.put(p)
            return products
        except (KeyError, ValueError, TypeError) as e:
            print('[Error json parser] ' + str(e))


class CategoryUrlParser:
    _parser = HtmlParser()

    def __init__(self):
        self._parser.addrule('ids', r'SearchBasedNavigationDisplay.clearAll\(\'(.*?)\'\)')

    def __del__(self):
        self._parser = None

    def findall_ids(self, src):
        ids = self._parser.findall('ids', src)
        if len(ids) == 0:
            return None
        return ids
